package com.screwdriver.jso.processor;

import com.screwdriver.jso.processor.utils.InterfaceVisitorAdapter;
import com.screwdriver.jso.processor.utils.TypeResolver;
import com.screwdriver.jso.processor.utils.TypeUtil;
import com.sun.mirror.apt.AnnotationProcessorEnvironment;
import com.sun.mirror.declaration.InterfaceDeclaration;
import com.sun.mirror.declaration.MethodDeclaration;
import com.sun.mirror.type.DeclaredType;
import com.sun.mirror.type.InterfaceType;
import com.sun.mirror.type.TypeMirror;

import java.io.PrintWriter;
import java.util.HashSet;
import java.util.Set;
import java.util.logging.Logger;

@SuppressWarnings("deprecation")
public class ImportsGeneratingInterfaceVisitor extends InterfaceVisitorAdapter {

    private static final Logger log = Logger.getLogger(ImportsGeneratingInterfaceVisitor.class.getCanonicalName());

    private AnnotationProcessorEnvironment environment;
    private final PrintWriter sourceWriter;
    private Set<DeclaredType> importsAlreadyAdded = new HashSet<DeclaredType>();
    private InterfaceDeclaration rootType;

    public ImportsGeneratingInterfaceVisitor(AnnotationProcessorEnvironment environment, PrintWriter sourceWriter) {
        this.environment = environment;
        this.sourceWriter = sourceWriter;
    }

    @Override
    public void visitRoot(InterfaceDeclaration rootType) {
        this.rootType = rootType;
    }


    @Override
    public void visitMethod(InterfaceType declaringSuperInterface, MethodDeclaration md) {
        if (!TypeUtil.isMethodImplementedByOtherJso(md, rootType)) {

            TypeResolver returnType1 = new TypeResolver(environment, rootType, declaringSuperInterface, md.getReturnType());

            for (DeclaredType type : returnType1.getInvolvedTypes()) {
                if (!importsAlreadyAdded.contains(type)) {
                    sourceWriter.println(String.format("import %s;", type.getDeclaration().getQualifiedName()));
                    importsAlreadyAdded.add(type);
                }
            }
        }
    }

}